﻿/*
*   学员信息页面
*/
angular.module('jisuStuHome')
.controller('questionDetailController', ['$scope', '$rootScope', '$state', 'StuRequestTrain', 'interlocutionservice', 'sysUserInfo', 'Msg', 'MsgCon', 'T', 'LS', function ($scope, $rootScope, $state, ST, IS, sysUserInfo, Msg, MsgCon, T, LS) {


    //初始
    $scope.init = function () {
        $scope.userInfo = sysUserInfo.getuserinfo(); //用户
        $rootScope.parstr = "home.interlocution";
        $rootScope.twoparstr = "home.interlocution.questiondetail";
        $scope.quesInfo = LS.getLS($scope.userInfo.user_ID + '_ques'); //当前列表所属栏目对象
        if ($scope.quesInfo.spare != undefined && $scope.quesInfo.spare.length > 0 && typeof ($scope.quesInfo.spare) == "string") {
            $scope.quesInfo.spare = JSON.parse($scope.quesInfo.spare);
        }
        $scope.colInfo = LS.getLS($scope.userInfo.user_ID + '_col'); //当前列表所属栏目对象

        $scope.backHome();
        //查询的参数
        $scope.params = {
            qaid: $scope.quesInfo.qaid,
            knowledgeid: "",
            userid: sysUserInfo.getuserinfo().user_ID,
            orgid: sysUserInfo.getuserinfo().organization_ID,
            parentId: "0",
            searchTxt: "",
            orderby: "1",
            pageIndex: 1,
            pageSize: 10
        };

        //是否是专栏管理人员
        if ($scope.colInfo && $scope.colInfo.userXid && $scope.colInfo.userXid.indexOf($scope.userInfo.user_ID) != -1) {
            $scope.xmanager = true;
        } else {
            $scope.xmanager = false;
        }
    }

    //返回主页，专栏列表
    $scope.backHome = function () {
        $scope.List = [];
        if ($scope.quesInfo == null || $scope.quesInfo == "" || $scope.quesInfo == undefined) {
            //返回首页
            if ($scope.colInfo == null || $scope.colInfo == "" || $scope.colInfo == undefined) {
                $rootScope.twoparstr = "home.interlocution";
                //返回问答页
            } else {
                $rootScope.twoparstr = "home.interlocution.questionlist";
            }
            $state.go($rootScope.twoparstr);
        }

    }
    $scope.init();

    //修改预览次数
    $scope.updatePreviewNum = function () {
        IS.addPreviewNum({ qaid: $scope.quesInfo.qaid }).then(function (response) {
            $scope.Loading = false;
            if (response.errorcode == "0") {
                $scope.quesInfo.browseNum = $scope.quesInfo.browseNum + 1;
                $scope.reSetQues();
            } else {
                Msg.error("修改异常!")
            }
        }, function errorCallback() {
            $scope.Loading = false;
            console.log("连接服务器失败！");
        });
    }
    $scope.updatePreviewNum();

    //重新向缓存设值，防止刷新数据对不上
    $scope.reSetQues = function () {
        LS.getLS($scope.userInfo.user_ID + '_ques', $scope.quesInfo);
    }
    //修改审核状态
    $scope.toPass = function (item) {
        IS.toPass({ qaid: item.qaid, userid: sysUserInfo.getuserinfo().user_ID, username: sysUserInfo.getuserinfo().user_Name }).then(function (response) {
            if (response.errorcode == "0") {
                if (item.state == 2) {
                    item.state = 1;
                    Msg.success("提示", "修改成功，学员将不再看见此问答！");
                } else {
                    item.state = 2;
                    Msg.success("审核成功");
                }
            } else {
                Msg.error("审核异常!")
            }
        }, function errorCallback() {
            $scope.Loading = false;
            console.log("连接服务器失败！");
        });
    }
    /**********************************查询***********************************/
    $scope.List = [];
    $scope.numCount = 0;

    //获取回复的列表
    $scope.getList = function (item) {
        if (item == undefined) {
            $scope.params.parentId = 0;
        }
        IS.findReplay($scope.params).then(function (response) {
            $scope.Loading = false;
            if (response.errorcode == "0") {
                if ($scope.params.parentId != 0) {
                    item.ziList = response.datas;
                    item.ziList.forEach(function (data, index) {
                        if (data.pointNum == undefined) {
                            data.pointNum = 0;
                        }
                    });
                    item.numCount = response.numCount;
                } else {
                    $scope.List = $scope.List.concat(response.datas);
                    $scope.List.forEach(function (data, index) {
                        if (data.pointNum == undefined) {
                            data.pointNum = 0;
                        }
                        if (data.spare != undefined && data.spare.length > 0 && typeof (data.spare) == "string") {
                            data.spare = JSON.parse(data.spare);
                        }
                    });
                    $scope.numCount = response.numCount;
                }
            } else {
                Msg.error("查询异常!")
            }
        }, function errorCallback() {
            $scope.Loading = false;
            console.log("连接服务器失败！");
        });
    }
    //查询该问答关联的分类
    $scope.getClass = function () {
        IS.findClassByQuesId({ quesid: $scope.quesInfo.qaid }).then(function (response) {
            if (response.errorcode == "0") {
                $scope.classList = response.datas;
            } else {
                Msg.error("查询分类失败!")
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });
    }

    //收藏问答
    $scope.collectionQuestion = function () {
        $scope.Loading = true;
        //新增
        if (!$scope.quesInfo.isCollection) {
            var obj = { xid: $scope.quesInfo.qaid, xname: $scope.quesInfo.title, xtype: "2", userid: sysUserInfo.getuserinfo().user_ID, orgid: sysUserInfo.getuserinfo().organization_ID };
            IS.saveCollection({ data: JSON.stringify(obj) }).then(function (response) {
                $scope.Loading = false;
                if (response.errorcode == "0") {
                    Msg.success("收藏成功！");
                    $scope.quesInfo.isCollection = !$scope.quesInfo.isCollection;
                    $scope.reSetQues();
                } else {
                    Msg.error("收藏失败!")
                }
            }, function errorCallback() {
                $scope.Loading = false;
                console.log("连接服务器失败！");
            });
            //取消
        } else {
            IS.delCollection({ qaid: $scope.quesInfo.qaid, userid: sysUserInfo.getuserinfo().user_ID }).then(function (response) {
                $scope.Loading = false;
                if (response.errorcode == "0") {
                    Msg.success("取消成功！");
                    $scope.quesInfo.isCollection = !$scope.quesInfo.isCollection;
                    $scope.reSetQues();
                } else {
                    Msg.error("取消失败!")
                }
            }, function errorCallback() {
                $scope.Loading = false;
                console.log("连接服务器失败！");
            });
        }

    }
    //回复
    $scope.showReplay = function (item) {

        if (item.showplay) {
            item.showplay = false;
        } else {
            //收起其他的回复框
            $scope.List.forEach(function (data, index) {
                data.showplay = false;
            });
            //展开当前的
            item.showplay = true;
            item.myText = "";
            $scope.params.parentId = item.areplayId;
            $scope.getList(item);
        }
    }
    //添加子集回复(回车)
    $scope.AddZiQuesEnter = function (item, e) {

        var keycode = window.event ? e.keyCode : e.which;
        if (keycode == 13) {
            $scope.replayInfo.areplayFid = item.areplayId; //父id
            $scope.replayInfo.areplayContent = item.myText;
            $scope.replayInfo.spare = []; //子集回复不添加附件
            $scope.addReplay(item);
        }
    }
    //添加子集回复（按钮）
    $scope.AddZiQuesButton = function (item) {

        $scope.replayInfo.areplayFid = item.areplayId; //父id
        $scope.replayInfo.areplayContent = item.myText;
        $scope.addReplay(item);
    }
    /***************************************新增***************************************/
    //初始新增
    $scope.initAdd = function () {
        //新增的对象
        $scope.replayInfo = {
            qaId: $scope.quesInfo.qaid,
            areplayFid: "0",
            areplayContent: "",
            replyUserId: sysUserInfo.getuserinfo().user_ID,
            replyUserName: sysUserInfo.getuserinfo().user_Name,
            replyAvatar: sysUserInfo.getuserinfo().user_Img,
            replyOrgId: sysUserInfo.getuserinfo().organization_ID,
            spare: []//附件的json
        };
    }
    $scope.initAdd();
    $scope.myText = "";
    $scope.oldText = "";
    $scope.AddQuesEnter = function (e) {
        var keycode = window.event ? e.keyCode : e.which;
        if (keycode == 13) {
            if ($scope.myText.length <= 0) {
                Msg.warning("请输入回复内容！");
                return;
                console.log($scope.oldText);
            } else {
                $scope.addReplay();
            }
        }
    }
    //新增回复的方法
    $scope.addReplay = function (item) {
        //新增
        if (item == undefined) {
            if ($scope.myText.length <= 0) {
                Msg.warning("请输入回复内容！");
                return;
                console.log($scope.oldText);
            }
            $scope.replayInfo.areplayContent = $scope.myText;
            if ($scope.fileObj.name != undefined && $scope.fileObj.name.length > 0) {
                $scope.replayInfo.spare.push($scope.fileObj);
            }
        }
        $scope.replayInfo.spare = JSON.stringify($scope.replayInfo.spare);
        IS.saveReplay({ data: JSON.stringify($scope.replayInfo) }).then(function (response) {
            if (response.errorcode == "0") {
                //var item = ;
                if ($scope.replayInfo.areplayFid != "0") {
                    if (response.data.spare != undefined && response.data.spare.length > 0) {
                        response.data.spare = JSON.parse(response.data.spare);
                    }
                    item.ziList.push(response.data);
                    item.myText = "";
                    $scope.reSetQues();
                } else {
                    if (response.data.spare != undefined && response.data.spare.length > 0) {
                        response.data.spare = JSON.parse(response.data.spare);
                    }
                    $scope.List.push(response.data);
                    $scope.fileObj = {};
                    $scope.myText = "";
                }
                $rootScope.TJInfo.answerNum = $rootScope.TJInfo.answerNum + 1; //修改我的回答数量
                $scope.quesInfo.replyNum = $scope.quesInfo.replyNum + 1;
                $scope.initAdd();
            } else {
                Msg.error("回复失败!")
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });
    }
    //点赞，或取消
    $scope.dianzhan = function (item) {
        var s = 1;
        //取消点赞
        if (item.isPoint) {
            s = 2;
        }
        IS.modifyPoint({ userid: sysUserInfo.getuserinfo().user_ID, type: "1", state: s, xid: item.areplayId }).then(function (response) {
            if (response.errorcode == "0") {
                if (item.isPoint) {
                    item.pointNum = item.pointNum - 1;
                } else {
                    item.pointNum = item.pointNum + 1;
                }
                item.isPoint = !item.isPoint;
            } else {
                Msg.error("操作失败!")
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });
    }
    //加载更多
    $scope.loadMore = function () {
        $scope.params.pageIndex = $scope.params.pageIndex + 1;
        $scope.getList();
    }

    //设为取消满意
    $scope.setManyi = function (item) {
        IS.setManyi({ replayid: item.areplayId, qaid: $scope.quesInfo.qaid }).then(function (response) {
            if (response.errorcode == "0") {
                //请求的是设为满意，需要取消其他的满意
                if (!item.isSolve) {
                    $scope.List.forEach(function (data, index) {
                        data.isSolve = false;
                    })

                }
                //如果回答的人是当前登陆的人
                //修改采纳数量
                if (item.replyUserId == sysUserInfo.getuserinfo().user_ID) {
                    if (!item.isSolve) {
                        $rootScope.TJInfo.adoptionNum = $rootScope.TJInfo.adoptionNum + 1;
                    } else {
                        $rootScope.TJInfo.adoptionNum = $rootScope.TJInfo.adoptionNum - 1;
                    }
                }
                item.isSolve = !item.isSolve;
                Msg.success("操作成功");
            } else {
                Msg.error("回复失败!")
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });
    }
    /*************************************删除*********************************************/
    //删除父
    $scope.delReplay = function (item) {
        IS.delReplay({ replayid: item.areplayId, userid: sysUserInfo.getuserinfo().user_ID, qaid: $scope.quesInfo.qaid }).then(function (response) {
            if (response.errorcode == "0") {
                $scope.quesInfo.replyNum = $scope.quesInfo.replyNum - 1;
                $scope.numCount = $scope.numCount - 1;
                $scope.reSetQues();
                Msg.success("删除成功");
                //遍历子集，修改我的回答数
                if (item.ziList != undefined && item.ziList.length > 0) {
                    item.ziList.forEach(function (data, index) {
                        if (data.replyUserId == sysUserInfo.getuserinfo().user_ID) {
                            $rootScope.TJInfo.answerNum = $rootScope.TJInfo.answerNum - 1;
                        }
                    });
                }
                //比对父级，修改我的回答数
                if (item.replyUserId == sysUserInfo.getuserinfo().user_ID) {
                    $rootScope.TJInfo.answerNum = $rootScope.TJInfo.answerNum - 1;
                }
                //移除
                $scope.List.forEach(function (data, index) {
                    if (data.areplayId == item.areplayId) {
                        $scope.List.splice(index, 1);
                    }
                })
            } else {
                Msg.error("回复失败!")
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });
    }
    //删除子
    $scope.delZiReplay = function (item, id) {
        IS.delReplay({ replayid: id, userid: sysUserInfo.getuserinfo().user_ID, qaid: $scope.quesInfo.qaid }).then(function (response) {
            if (response.errorcode == "0") {
                item.ziList.forEach(function (data, index) {
                    if (data.areplayId == id) {
                        $scope.List.splice(index, 1);
                    }
                });
                $scope.quesInfo.replyNum = $scope.quesInfo.replyNum - 1;
                $scope.numCount = $scope.numCount - 1;
                $scope.reSetQues();
                //修改回答数量
                if (item.replyUserId == sysUserInfo.getuserinfo().user_ID) {
                    $rootScope.TJInfo.answerNum = $rootScope.TJInfo.answerNum - 1;
                }
                Msg.success("删除成功");
            } else {
                Msg.error("回复失败!")
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });
    }
    $scope.isDelQues = false;
    // 删除问答
    $scope.delQuestionInfo = function () {
        //提示框
        MsgCon.delnoicon().then(function (flag) {   // 删除弹框
            if (flag) {
                // 发送请求
                IS.delQA({ qaid: $scope.quesInfo.qaid, userid: sysUserInfo.getuserinfo().user_ID, colid: $scope.quesInfo.xid }).then(function (respose) {
                    if (respose.errorcode == "0") {
                        Msg.success("删除成功！");
                        //修改提问数量
                        if ($scope.quesInfo.questionerId == sysUserInfo.getuserinfo().user_ID) {
                            $rootScope.TJInfo.askNum = $rootScope.TJInfo.askNum - 1;
                        }
                        //清除
                        $scope.isDelQues = true;
                        LS.setLS($scope.userInfo.user_ID + '_ques', "");
                        $scope.quesInfo = {};
                    } else {
                        Msg.error("操作失败！");
                    }
                }, function errorCallback() {
                    console.log("连接服务器失败！");
                });
            }
        }, function (p) { console.log('error') });
    }
    /*********************************************************************/
    //配置分页
    $scope.paginationConf = {
        currentPage: 1, // 当前页码
        totalItems: 0,  // 总的记录数
        itemsPerPage: 10, // 每页显示多少条        
        perPageOptions: [10, 20],   // 每页显示记录数        
        onChange: function () {
            $scope.paginationConf.currentPage = $scope.paginationConf.currentPage == 0 ? 1 : $scope.paginationConf.currentPage;
            $scope.params.pageIndex = $scope.paginationConf.currentPage;
            $scope.params.pageSize = $scope.paginationConf.itemsPerPage;
            $scope.getList();
        }
    };
    /***************************************初始*********************************************/

    $scope.getClass(); //获取分类
    $scope.getList(); //获取回复

    /********************************************附件***********************************************/
    $scope.fileObj = {}; //附件对象
    //添加附件
    $scope.addFile = function () {
        document.getElementById("FJUpload").click();
    }
    var trainupfile = $scope.uploader;
    trainupfile.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {     // 选择文件后失败       0
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    trainupfile.onAfterAddingFile = function (fileItem) {  // 选择文件后 （成功）   0          
        console.info('onAfterAddingFile', fileItem);
        if (trainupfile.isUploading) {
            Msg.warning("有文件正在上传。。");
            return;
        } else {
            var upfileparam = "?orgid=" + sysUserInfo.getuserinfo().organization_ID + "&userid=" + sysUserInfo.getuserinfo().user_ID;
            //上传文件路径
            fileItem.url = ST.uploadEnclosure(upfileparam);
        }
    };
    trainupfile.onAfterAddingAll = function (addedFileItems) { // 选择文件后添加到队列   1 
        console.info('onAfterAddingAll', addedFileItems);
        if (trainupfile.isUploading) {
            Msg.warning("有文件正在上传。。");
            return;
        } else {
            trainupfile.uploadAll();
        }
    };
    // 开始上传
    trainupfile.onBeforeUploadItem = function (item) {    // 2 上传之前一项
        console.info('onBeforeUploadItem', item);
    };
    trainupfile.onProgressItem = function (fileItem, progress) {   // 3 上传进度
        console.info('onProgressItem', fileItem, progress);
    };
    trainupfile.onProgressAll = function (progress) {      //4 队列进度
        console.info('onProgressAll', progress);
    };
    trainupfile.onSuccessItem = function (fileItem, response, status, headers) {   // 5上传成功
        console.info('onSuccessItem', fileItem, response, status, headers); //fileItem 请求信息 response: 返回值status: 返回状态  headers: 请求头 
        //                 $scope.path = response.errormsg; //文件路径
        //                 $scope.filename = fileItem.name; //文件名称
        if (response.errorcode == 0) {
            $scope.fileObj = { name: fileItem.file.name, path: response.errormsg, type: fileItem.file.name.split(".")[1] };
            Msg.success("上传成功！");
        } else if (response.errorcode == "10002") {
            Msg.warning("文件过大，请重新选择！");
        } else if (response.errorcode == "10001") {
            Msg.warning("文件格式错误，请选择图片文件！");
        } else {
            Msg.error("上传失败！" + response.errorcode);
        }
    };
    trainupfile.onErrorItem = function (fileItem, response, status, headers) {     // 5上传失败
        console.info('onErrorItem', fileItem, response, status, headers);
    };
    trainupfile.onCancelItem = function (fileItem, response, status, headers) {    //5取消上传
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    trainupfile.onCompleteItem = function (fileItem, response, status, headers) {  //6     单文件上传完成
        console.info('onCompleteItem', fileItem, response, status, headers);

    };
    trainupfile.onCompleteAll = function () {  // 6 单文件上传完成或者队列上传完成的时候
        console.info('onCompleteAll');
    };
    /*********************************************文件上传结束**********************************************/
} ]);




